/**
 * 系统提示消息数据字典管理器
 * 依赖：custom/plugins/yufp.service.js
 * created by liujie1 2019-5-27
 */
(function (yufp, window, factory) {
  var exports = factory(yufp, window, window.document);
  if (typeof define === 'function') {
    define(exports);
  }
  window.yufp.messageLookup = exports;
}(yufp, window, function (yufp, window, document) {
  /**
     * 消息统一数据字典管理器
     * @constructor
     */
  function MessageLookup () {
    var _options = {
      lookupMgrMessage: {}, // 内存字典对象
      remoteUrl: backend.appCommonService + '/api/provider/getMessage', // 远程URL
      remoteParamName: 'code', // 远程参数名
      limit: false, // 是否开启字典长度超过limitlength长度转存
      limitLength: 100, // 字典长度超过100，直接存储于localstorage
      prefix: 'YUFP-MESSAGE'// 超长字典前缀
    };
    yufp.extend(this, _options);
  }

  /**
     * private
     * 加载指定远程数据字典
     * @param types  String
     *    GENDER_TYPE
     *    GENDER_TYPE,USER_STATUS,SYSTEM_STATUS
     * @param callback 暂且未处理callback，20180731
     */
  MessageLookup.prototype.loadRemote = function (type, callback) {
    var _this = this;
    // TODO 暂且未考虑字典请求中队列
    var message = null;
    _this.forceLoad(type, function (data) {
      message = data || [];
      if (!_this.limit) {
        _this.lookupMgrMessage[type] = message;
      } else {
        if (data[type].length < _this.limitLength) {
          _this.lookupMgrMessage[type] = message;
        } else {
          _this.storagePut(_this.prefix + type, message);
        }
      }
      type = null;
    });
    return message;
  };

  /**
     * private
     * 强制刷新远程字典
     * @param types
     * @param callback
     */
  MessageLookup.prototype.forceLoad = function (types, callback) {
    var _this = this;
    var param = {};
    param[_this.remoteParamName] = types;
    yufp.service.request({
      url: _this.remoteUrl,
      async: false,
      method: 'get',
      data: param,
      callback: function (code, msg, response) {
        if (code == 0 && response && yufp.type(callback) == 'function') {
          callback.call(this, response);
        }
      }
    });
  };


  MessageLookup.prototype.storagePut = function (type, array) {
    yufp.sessionStorage.put(this.prefix + type, JSON.stringify(array));
  };

  MessageLookup.prototype.storageGet = function (type) {
    var lookup = yufp.sessionStorage.get(this.prefix + type);
    if (lookup) {
      lookup = JSON.parse(lookup);
    } else {
      lookup = undefined;
    }
    return lookup;
  };

  /**
     * 将字典注册到字典管理器中
     * @param type string,必须
     * @param callback ，loadRemote暂且未处理此参数，故无效20180731
     */
  MessageLookup.prototype.get = function (type, callback) {
    var _this = this;
    var obj = _this.lookupMgrMessage[type] || _this.storageGet[type];
    if (obj) {
      return obj;
    } else {
      return _this.loadRemote.call(this, type, callback);
    }
  };
  return new MessageLookup();
}));
